var ParserConfig = {
    imgFileEle: document.getElementById('img'),
    imgShowEle: document.getElementById('img-show'),
    imgShowHiddenEle: document.getElementById('img-show-hidden'),
    imgSeparateEle: document.getElementById('img-separate'),
    editorView: document.getElementById('editor-view'),
}

var PicParser = function() {
    this.parse = function() {
            ParserConfig.imgShowEle.innerHTML = null;
            this.load(false);
        },
        this.append = function() {
            this.load(true);
        },
        this.load = function(append) {
            var imgEle = document.createElement('img');
            ParserConfig.imgShowHiddenEle.append(imgEle);
            var imgShow = createImgShow();
            imgShowEle.appendChild(imgShow);
            var reader = new FileReader();
            var file = append ? ParserConfig.imgFileAppendEle.files[0] : ParserConfig.imgFileEle.files[0];
            reader.readAsDataURL(file);
            var ref = imgShow.getAttribute('source');
            reader.onload = ({ target }) => {
                imgShow.src = target.result;
                imgEle.src = target.result;
                imgEle.onload = function() {
                    updateImgWH(append, imgEle);
                }
                var img = createImg(target.result, 'auto');
                img.src = target.result;
                img.setAttribute('ref', ref);
                append ? appendElement(ParserConfig.imgSeparateEle, img) : ParserConfig.imgSeparateEle.appendChild(img);
            }
        }
}

var GifParser = function() {
    this.parse = function() {
            ParserConfig.imgShowEle.innerHTML = null;
            this.load(false);
        },
        this.append = function() {
            this.load(true);
        },
        this.load = function(append) {
            var imgEle = document.createElement('img');
            ParserConfig.imgShowHiddenEle.append(imgEle);
            var file = append ? ParserConfig.imgFileAppendEle.files[0] : ParserConfig.imgFileEle.files[0];
            var imgBlob = URL.createObjectURL(file);
            imgEle.setAttribute('rel:animated_src', imgBlob)
            var imgShow = createImgShow();
            imgShow.src = imgBlob;
            imgShowEle.appendChild(imgShow);
            var rub = new SuperGif({
                gif: imgEle,
                auto_play: 0
            });

            rub.load(function() {
                var width = 0;
                var rubLen = rub.get_length();
                updateImgWH(append, imgEle);
                if (!append) {
                    var canvas = document.querySelector('#img-show-hidden canvas');
                    width = ParserConfig.imgSeparateEle.clientWidth / rubLen;
                } else {
                    width = ParserConfig.imgSeparateEle.children[0].style.width;
                }
                var appendChild = false;
                if (append && !currentAddEle.parentElement.nextElementSibling) {
                    appendChild = true;
                }
                var ref = imgShow.getAttribute('source');
                for (var i = 1; i <= rubLen; i++) {
                    rub.move_to(i);
                    var src = rub.get_canvas().toDataURL('image/png', 0.8);
                    // var src = rub.get_canvas().toDataURL('image/jpeg', 0.8);
                    var img = createImg(src, width);
                    img.setAttribute('ref', ref);
                    append ? appendElement(ParserConfig.imgSeparateEle, img, appendChild) : ParserConfig.imgSeparateEle.appendChild(img);
                }
                setTimeout(function() {
                    rub.play()
                }, 1000);
            })
        }
}

var updateImgWH = function(append, imgEle) {
    if (append) {
        var w = ParserConfig.imgShowHiddenEle.getAttribute("img-width");
        var h = ParserConfig.imgShowHiddenEle.getAttribute("img-height");
        if (imgEle.width > w) {
            ParserConfig.imgShowHiddenEle.setAttribute("img-width", imgEle.width);
        }
        if (imgEle.height > h) {
            ParserConfig.imgShowHiddenEle.setAttribute("img-height", imgEle.height);
        }
    } else {
        ParserConfig.imgShowHiddenEle.setAttribute("img-width", imgEle.width);
        ParserConfig.imgShowHiddenEle.setAttribute("img-height", imgEle.height);
    }
}

var appendElement = function(parent, ele, append) {
    if (currentAddEle.className.indexOf('img-add-left') != -1) {
        parent.insertBefore(ele, currentAddEle.parentElement);
    } else {
        append ? parent.appendChild(ele) : parent.insertBefore(ele, currentAddEle.parentElement.nextElementSibling);
    }
}

var createImgShow = function() {
    var imgShow = document.createElement('img');
    var ref = Math.random();
    imgShow.setAttribute("source", ref);
    imgShow.ondblclick = function(e) {
        var tag = e.currentTarget;
        var child = ParserConfig.imgSeparateEle.children;
        if (child && child.length) {
            var ref = tag.getAttribute('source');
            for (var i = child.length - 1; i >= 0; i--) {
                if (child[i].getAttribute('ref') == ref) {
                    child[i].remove();
                }
            }
        }
        tag.remove();
    }
    return imgShow;
}

var createImg = function(src, width) {
    var imgDiv = document.createElement('div');
    //del
    var imgDel = document.createElement('div');
    imgDiv.className = "img-separate-div";
    imgDel.className = "img-delete-view";
    imgDel.innerHTML = "X";
    //add
    var imgAddL = document.createElement('div');
    imgAddL.innerHTML = "+";
    imgAddL.className = "img-add img-add-left";
    imgAddL.onclick = addImg;
    var imgAddR = document.createElement('div');
    imgAddR.innerHTML = "+";
    imgAddR.className = "img-add img-add-right";
    imgAddR.onclick = addImg;
    //img
    var img = document.createElement('img');
    img.src = src;
    setImgWH(imgDiv, width);
    setImgWH(img, width);
    var imgDevTime = 0;
    imgDiv.onclick = function(e) {
        imgDevTime = imgDevTime + 1;
        if (imgDevTime == 1) {
            var target = e.target;
            setTimeout(function() {
                try {
                    if (imgDevTime == 1) {
                        imgClick(target);
                    } else if (imgDevTime >= 2) {
                        imgDbClick(target);
                    }
                } catch (error) {
                    console.error(error);
                }
                imgDevTime = 0;
            }, 333);
        }
    }

    function imgClick(img) {
        ParserConfig.editorView.innerHTML = null;
        var canvasEle = document.createElement("canvas");
        canvasEle.id = "editor-view-canvas";
        canvasEle.width = "500";
        canvasEle.height = "500";
        ParserConfig.editorView.appendChild(canvasEle);
        var btnDiv = document.createElement('div');
        var okBtn = document.createElement('button');
        okBtn.innerText = "Ok";
        btnDiv.appendChild(okBtn);
        var closeBtn = document.createElement('button');
        closeBtn.innerText = "Close";
        btnDiv.appendChild(closeBtn);
        ParserConfig.editorView.appendChild(btnDiv);
        ParserConfig.editorView.style.display = 'block';
        var canvas = new fabric.Canvas('editor-view-canvas');
        var shadowText1 = new fabric.IText("你还好吗？", {
            fill: 'rgba(0,255,0,1)',
            shadow: 'rgba(0,0,0,0.3) 5px 5px 5px',
            fontStyle: 'italic',
            fontFamily: 'Hoefler Text'
        });
        shadowText1.shadow.color = 'rgba(255,0,0,0.3)';
        okBtn.onclick = function() {
            img.src = canvas.toDataURL()
        }
        closeBtn.onclick = function() {
            ParserConfig.editorView.style.display = 'none';
            ParserConfig.editorView.innerHTML = null;
        }
        addImgToCanvas(canvas, img);
        canvas.add(shadowText1);

    }

    function addImgToCanvas(canvas, imgToAdd) {
        var obj = new fabric.Image(imgToAdd, {
            left: 0,
            top: 0,
            width: imgToAdd.naturalWidth,
            height: imgToAdd.naturalHeight,
            crossOrigin: 'anonymous',
            copy: true,
        });
        canvas.add(obj);
    }

    function imgDbClick(target) {
        var p = target.parentElement;
        p.className = p.className ? p.className : "";
        if (p.className.indexOf('img-delete') == -1) {
            p.className = p.className + " img-delete";
            p.getElementsByClassName('img-delete-view')[0].style.display = "block";
        } else {
            p.className = p.className.replaceAll("img-delete", "");
            p.getElementsByClassName('img-delete-view')[0].style.display = "none";
        }
    }
    imgDiv.appendChild(imgAddL);
    imgDiv.appendChild(imgAddR);
    imgDiv.appendChild(img);
    imgDiv.appendChild(imgDel);
    return imgDiv;
}

var currentAddEle;
var addImg = function(e) {
    var ele = e.currentTarget;
    currentAddEle = ele;
    var imgFileEle = document.getElementById('img-hidden');
    imgFileEle.click();
    e.stopPropagation();
}

var setImgWH = function(ele, width) {
    width = typeof width == 'number' ? width + 'px' : width;
    ele.style.minHeight = 100 + 'px';
    ele.style.height = width;
    ele.style.maxHeight = 150 + 'px';
    ele.style.minWidth = 100 + 'px';
    ele.style.width = width;
    ele.style.maxWidth = 150 + 'px';
}

var createImgFileHidden = function() {
    if (document.getElementById("img-hidden")) {
        return;
    }
    var ele = document.createElement('input');
    ele.id = "img-hidden";
    ele.type = "file";
    ele.hidden = true;
    ele.onchange = function(e) {
        var files = e.target.files;
        if (files.length > 0) {
            var fName = files[0].name;
            ParserConfig.imgShowHiddenEle.innerHTML = null;
            var imgEle = document.createElement('img');
            ParserConfig.imgShowHiddenEle.appendChild(imgEle);
            if (currentAddEle.className.indexOf('img-add-left') != -1) {
                if (fName.endsWith('.gif')) {
                    gifParser.append();
                } else if (/\.(?:jpg|jpeg|png|bmp)$/i.test(fName)) {
                    picParser.append();
                }
            } else if (currentAddEle.className.indexOf('img-add-right') != -1) {
                if (fName.endsWith('.gif')) {
                    gifParser.append();
                } else if (/\.(?:jpg|jpeg|png|bmp)$/i.test(fName)) {
                    picParser.append();
                }
            }
        }
        ele.value = null;
    }
    document.body.appendChild(ele);
    ParserConfig.imgFileAppendEle = document.getElementById('img-hidden');
}
createImgFileHidden();